<?php
namespace app\admin\controller;

use think\Request;
use think\Db;

class Goodscate extends Base
{
    /**
     * 分类列表
     */
    // http://127.0.0.1/auth/Index/index
    public function index()
    {
    	$list=$this->getCate();
    	if ($list) {
    		$data['menu'] = $this->menu2Html( $this->toTree($list) );
    	}else{
    		$data['menu'] = '';
    	}
        //商品分类
        $cat = CAT('goods_category',array('cate_id','cate_pid','cate_name','fullname'),'cate_status=1');
        $cate_tree = $cat->getList(0);
        $data['cate_tree'] = $cate_tree;
        // $cat = Db::field('*,cate_name as fullname')->name('goods_category')->where(['cate_status'=>1,'cate_pid'=>0])->select();
        // $data['cate_tree'] = $cat;
        //广告位
        $adp_list = Db::name('adposition')->order('adp_id asc')->select();
        $data['adp_list'] = $adp_list;
        if (Request()->isAjax()) {
            $this->success('success','',$data);
        }else{
            return $this->fetch('index',$data);
        }
		
    }

    private function getCate(){
    	$list = Db::name('goods_category')->order('listorder asc')->select();
    	return $list;
    }

	    /**
	 * 递归生成树
	 * @param  [type]  $data  [description]
	 * @param  integer $pid   [description]
	 * @param  boolean $reset [description]
	 * @return [type]         [description]
	 */
	private function toTree($data = null, $pid = 0, $reset = false)
	{
	    static $node = [];
	    if(empty($data) || !is_array($data) ) {
	        return [];
	    }
	    if( $reset ) {
	        $node = [];
	    }
	    //父节点
	    if( $node === [] ) {
	        foreach ($data as $item) {
	            if($item['cate_pid'] == $item['cate_id']) {
	                //避免死循环
	                continue;
	            }
	            if( isset($node[$item['cate_pid']]) ) {
	                $node[$item['cate_pid']][] = $item;
	            }else {
	                $node[$item['cate_pid']] = [$item];
	            }
	        }
	    }
	    
	    $tree = [];
	    foreach( $data as $item ) {
	        if($pid == $item['cate_pid']) {
	            if( isset($node[$item['cate_id']]) ) {
	                $item['children'] = self::toTree($node[$item['cate_id']], $item['cate_id']);
	            }
	            $tree[] = $item;
	        }
	    }
	    return $tree;
	}

    /**
     * 格式化分类
     */
    private  function menu2Html($list)
    {
        $menu = '';
        if( is_array($list) ) {
            $menu .= '<ol class="dd-list">';
            foreach( $list as $li ) {
                $menu .= '<li class="dd-item" id="rid' . $li['cate_id'] . '" data-id="' . $li['cate_id'] . '" data-listorder="' . $li['listorder'] . '" data-pid="' . $li['cate_pid'] . '" title="' . $li['cate_name'] . '" data-icon="" data-module="" data-controller="" data-action="" data-ismenu="" data-adp_id="'. $li['adp_id'] .'" data-status="' . $li['cate_status'] . '">';
                $menu .= $this->buildHandle($li);
                
                if( isset($li['children']) ) {
                    $menu .= $this->menu2Html($li['children']);
                }
                $menu .= '</li>';
            }
    
            $menu .= '</ol>';
            return $menu;
        } else {
            return '';
        }
    }
    /**
     * 把单条权限组装成nestable样式
     */
    private function buildHandle($li){
        $menu = '<div class="dd-handle dd-status-'.$li['cate_status'].'">';
        if( !empty($li['icon']) ) {
            $menu .= '<i class=""></i> ';
        }
        $menu .= $li['cate_name'];

        // if($li['cate_status']) {
        //     $menu .= '<span class="dd-tool-right dd-nodrag"> <i class="fa fa-check-circle" title="点击禁用"></i>';
        //     if ($li['cate_pid'] == 0) {
        //          $menu .='<i class="fa fa-plus" title="添加子菜单"></i>';
        //     }else{
        //         $menu .= '<i class="fa " title="二级不可添加">--</i>';
        //     }
        //      $menu .= '<i class="fa fa-edit" title="修改"></i> <i class="fa fa-trash-o" title="删除"></i> </span>';
        // } else {
        //     $menu .= '<span class="dd-tool-right dd-nodrag"> <i class="fa fa-ban" title="点击启用"></i> ';
        //     if ($li['cate_pid'] == 0) {
        //         $menu .= '<i class="fa fa-plus" title="添加子菜单"></i> ';
        //     }else{
        //         $menu .= '<i class="fa " title="二级不可添加">--</i> ';
        //     }

        //     $menu .= '<i class="fa fa-edit" title="修改"></i> <i class="fa fa-trash-o" title="删除"></i> </span>';
        // }

        if($li['cate_status']) {
            $menu .= '<span class="dd-tool-right dd-nodrag"> <i class="fa fa-check-circle" title="点击禁用"></i> <i class="fa fa-plus" title="添加子菜单"></i>  <i class="fa fa-edit" title="修改"></i> <i class="fa fa-trash-o" title="删除"></i> </span>';
        } else {
            $menu .= '<span class="dd-tool-right dd-nodrag"> <i class="fa fa-ban" title="点击启用"></i> <i class="fa fa-plus" title="添加子菜单"></i> <i class="fa fa-edit" title="修改"></i> <i class="fa fa-trash-o" title="删除"></i> </span>';
        
        }
        $menu .= '</div>';

        return $menu;
    }
    /**
     * 添加分类
     */
    public function add()
    {
        if ( Request::instance()->isPost() ) {
            $request = Request::instance();
            $data = $request->only('cate_pid,cate_name,cate_status,listorder,adp_id','post');
            isset($data['cate_status']) || $data['cate_status'] = 1;

            if( empty($data['cate_name']) ) {
            	$this->error('分类名不能为空');
            }

            //查看分类是否存在
            $isset = Db::name('goods_category')->where(['cate_name'=>$data['cate_name']])->find();
            $isset && $this->error('分类已经存在');

            if (
                Db::name( 'goods_category' )->insert($data)
            ) {
                $cate_id = Db::name('goods_category')->getLastInsID();
                $data = Db::name('goods_category')->where('cate_id',$cate_id)->find();
   
                $menu = '<li class="dd-item"  id="rid' . $data['cate_id'] . '" data-id="' . $data['cate_id'] . '" data-listorder="' . $data['listorder'] . '" data-pid="' . $data['cate_pid'] . '" title="' . $data['cate_name'] . '" data-icon="" data-module="" data-controller="" data-action="" data-ismenu="" data-adp_id="' .$data['adp_id']. '" data-status="' . $data['cate_status'] . '">'
                    .$this->buildHandle($data).'</li>';
                $this->success('添加成功','refresh',['menu'=>$menu,'cate_pid'=>'#rid'.$data['cate_pid']]);
            } else {
                $this->error('添加失败');
            }
            
        } else {
            $this->fetch();
        }
    }
    /**
     * 修改分类
     * -----------------
     * /get  : view
     * -----------------
     * /post : update 
     * @$_POST[
     *  'id'       => 'id',
     *  'pid' => '上级id',
     *  'title' => '名称',
     *  ...
     *  'listorder'     => '排序编号',
     *  'status' => '状态'
     *  ]
     *  修改多条
     *  $_POST[{'id' => 'id','title'=>'名称',...},{...},{...}]
     * -----------------
     * /call :
     * @param $id = int
     * @param $data = [
     *  'pid' => '上级id',
     *  'title' => '名称',
     *  ...
     *  'listorder'     => '排序编号',
     *  'status' => '状态'
     *  ]
     */
    public function edit($cate_id='', $data= '')
    {
        if ( Request::instance()->isPost() ) {
            //do update
            if( empty($cate_id) ){
                $cate_id = Request::instance()->get('cate_id','','number_int');
            }
            //修改单条
            if ( empty( $data) ) {
                $data = Request::instance()->only('cate_pid,cate_status,cate_name,listorder,adp_id','post');
            }
            
            if(isset($data['cate_pid']) && $data['cate_pid'] == $cate_id ) {
                unset($data['cate_pid']);
            }
            if (isset($data['cate_name']) && empty($data['cate_name'])) {
                $this->error('分类名不能为空');
            }
            
            if ( empty($data) ) {
            	$this->error('提交的数据错误');
            }

            //查看分类是否存在
            $isset = Db::name('goods_category')->where(['cate_name'=>$data['cate_name'], 'cate_id'=>['neq',$cate_id]])->find();
            $isset && $this->error('分类已经存在');

            if(
                Db::name('goods_category')
                ->where(['cate_id' => $cate_id])
                ->update($data) !== false
            ) {
                $data = Db::name('goods_category')->where('cate_id',$cate_id)->find();
            	$this->success('修改成功',url('index'),['cate_id'=>'#rid'.$cate_id,'handle'=>$this->buildHandle($data),'data'=>$data]);
            } else {
            	$this->error('修改失败');
            }
        } else {
            return $this->fetch();
        }
    }

    public function listorder($cate_id='', $data= ''){
    	if ( Request::instance()->isPost() ) {
            //do update
            if( empty($cate_id) ){
                $cate_id = Request::instance()->get('cate_id','','number_int');
            }
            if ( empty($cate_id) ){
                //批量修改
                $data = json_decode(file_get_contents('php://input'));
                if( is_array($data) ){
                    foreach ( $data as $item ) {
                        if ( is_object($item) && property_exists($item,'cate_id') && !empty($item->cate_id)) {
                            $column = [];
                            foreach(['cate_pid','cate_name','cate_status','listorder'] as $key) {
                                if( property_exists($item,$key) ) {
                                    $column[$key] = $item->$key;
                                }
                            }
                            if ( !empty($column) ) {
                                $this->listorder($item->cate_id, $column);
                            }
                        } else {
                            $this->error('提交数据错误');
                        }
                    }
                } else {
                	 $this->error('提交数据错误');
                }
                 $this->success('修改成功','');
            }else{

	           //修改单条
	            if ( empty( $data) ) {
	                $data = Request::instance()->only('cate_pid,cate_status,cate_name,listorder','post');
	            }
	            
	            if(isset($data['cate_pid']) && $data['cate_pid'] == $cate_id ) {
	                unset($data['cate_pid']);
	            }
	            if (isset($data['cate_name']) && empty($data['cate_name'])) {
	                $this->error('分类名不能为空');
	            }
	            
	            if ( empty($data) ) {
	            	$this->error('提交的数据错误');
	            }
	            Db::name('goods_category')->where(['cate_id' => $cate_id])->update($data);
	        }
        }
    }
    
    /**
     * 删除分类
     * @$_POST[id]
     * @$_POST[more] 连同子菜单一起删除，否则子菜单移至顶级菜单
     */
    public function delete(){
        $request = Request::instance();
        $id = $request->post('id','','number_int');
        if(empty($id)){
            $this->error('参数错误');
        }
        $list=$this->getCate();
        $ids = $this->tree2id($this->toTree($list,$id));
        $ids[] = $id;
        if(
            Db::name('goods_category')
            ->where('cate_id', 'in', $ids)
            ->delete()
        ) {
        	$this->success('删除成功');
        } else {
        	$this->error('删除失败');
        }
    
    }
 
    /**
     * 获取子分类ID
     */
    private  function tree2id($list)
    {
        $ids = [];
        if( is_array($list) ) {
            foreach( $list as $li ) {
                $ids[] = $li['cate_id'];
                if( isset($li['children']) ) {
                    $ids= array_merge($ids, $this->tree2id($li['children']));
                }
            }
            return $ids;
        } else {
            return [];
        }
    }

}
